package com.basker.pisces.orm.statement;

import java.sql.JDBCType;
import java.util.Collection;

import com.alibaba.fastjson.JSON;
import com.basker.pisces.core.meta.IDataField;
import com.basker.pisces.orm.data.meta.FieldMeta;

public class FieldObject {

    protected FieldMeta fieldMeta;
    protected Object value;
    protected Object oldValue;

    public FieldObject(FieldMeta fieldMeta, Object value) {
        this.fieldMeta = fieldMeta;
        this.value = this.resolveValue(value);
    }

    public IDataField getDataField() {
        return this.fieldMeta.getDataField();
    }

    public FieldMeta getFieldMeta() {
        return fieldMeta;
    }

    public String getName() {
        return this.fieldMeta.getName();
    }

    public Object getOldValue() {
        return oldValue;
    }

    public Object getValue() {
        return value;
    }

    public void setOldValue(Object oldValue) {
        this.oldValue = oldValue;
    }

    private Object resolveValue(Object value) {
        Class<?> fieldClass = fieldMeta.getDataField().getFieldClass();

        // 处理枚举数据
        if (value != null && fieldClass.isEnum()) {
            JDBCType jdbcType = fieldMeta.getDataField().getJDBCType();

            if (jdbcType.equals(JDBCType.INTEGER)) {
                return ((Enum<?>) value).ordinal();
            }

            return value.toString();
        }

        // 处理集合数据
        if (value != null && Collection.class.isAssignableFrom(fieldClass)) {
            return JSON.toJSONString(value);
        }

        return value;
    }
}
